﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Reddit.EndpointRetriever
{
    public class HttpEndpointRetriever : IEndpointRetriever<string>
    {
        protected IEndpointRetriever<string> urlEndpointRetriever;
        public HttpEndpointRetriever(IEndpointRetriever<string> urlEndpointRetriever)
        {
            this.urlEndpointRetriever = urlEndpointRetriever;
        }

        public string RetrieveEndpoint(Endpoint endpoint)
        {
            var url = this.urlEndpointRetriever.RetrieveEndpoint(endpoint);
            return this.sendWebRequest(url);
        }

        protected string sendWebRequest(string url)
        {
            string responseText;
            var request = System.Net.WebRequest.Create(url);
            var response = request.GetResponse();
            var responseStream = response.GetResponseStream();
            Encoding encode = System.Text.Encoding.GetEncoding("utf-8");
            var streamReader = new System.IO.StreamReader(responseStream, encode);

            responseText = streamReader.ReadToEnd();
            streamReader.Close();
            responseStream.Close();
            return responseText;
        }
    }
}
